import { ErrorInfo, PerformanceInfo, BehaviorInfo } from '../types';

// 生成唯一ID
export function generateId(): string {
  return Math.random().toString(36).substr(2, 9) + Date.now().toString(36);
}

// 生成会话ID
export function generateSessionId(): string {
  const sessionId = sessionStorage.getItem('error_monitor_session_id');
  if (sessionId) {
    return sessionId;
  }
  const newSessionId = generateId();
  sessionStorage.setItem('error_monitor_session_id', newSessionId);
  return newSessionId;
}

// 获取元素选择器
export function getElementSelector(element: Element): string {
  if (element.id) {
    return `#${element.id}`;
  }
  
  if (element.className) {
    const classes = element.className.split(' ').filter(Boolean);
    if (classes.length > 0) {
      return `.${classes.join('.')}`;
    }
  }
  
  if (element.tagName) {
    return element.tagName.toLowerCase();
  }
  
  return 'unknown';
}

// 获取元素文本内容
export function getElementText(element: Element): string {
  const text = element.textContent || element.innerText || '';
  return text.trim().substring(0, 100); // 限制文本长度
}

// 获取当前页面URL
export function getCurrentUrl(): string {
  return window.location.href;
}

// 获取用户代理
export function getUserAgent(): string {
  return navigator.userAgent;
}

// 获取浏览器信息
export function getBrowserInfo() {
  const ua = navigator.userAgent;
  const browser = {
    name: 'unknown',
    version: 'unknown',
    os: 'unknown'
  };

  // 检测浏览器
  if (ua.includes('Chrome')) {
    browser.name = 'Chrome';
  } else if (ua.includes('Firefox')) {
    browser.name = 'Firefox';
  } else if (ua.includes('Safari')) {
    browser.name = 'Safari';
  } else if (ua.includes('Edge')) {
    browser.name = 'Edge';
  } else if (ua.includes('MSIE') || ua.includes('Trident')) {
    browser.name = 'IE';
  }

  // 检测操作系统
  if (ua.includes('Windows')) {
    browser.os = 'Windows';
  } else if (ua.includes('Mac')) {
    browser.os = 'Mac';
  } else if (ua.includes('Linux')) {
    browser.os = 'Linux';
  } else if (ua.includes('Android')) {
    browser.os = 'Android';
  } else if (ua.includes('iOS')) {
    browser.os = 'iOS';
  }

  return browser;
}

// 获取屏幕信息
export function getScreenInfo() {
  return {
    width: screen.width,
    height: screen.height,
    availWidth: screen.availWidth,
    availHeight: screen.availHeight,
    colorDepth: screen.colorDepth,
    pixelDepth: screen.pixelDepth
  };
}

// 获取网络信息
export function getNetworkInfo() {
  const connection = (navigator as any).connection || (navigator as any).mozConnection || (navigator as any).webkitConnection;
  
  return {
    effectiveType: connection?.effectiveType || 'unknown',
    downlink: connection?.downlink || 0,
    rtt: connection?.rtt || 0,
    saveData: connection?.saveData || false
  };
}

// 深度克隆对象
export function deepClone<T>(obj: T): T {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  
  if (obj instanceof Date) {
    return new Date(obj.getTime()) as any;
  }
  
  if (obj instanceof Array) {
    return obj.map(item => deepClone(item)) as any;
  }
  
  if (typeof obj === 'object') {
    const cloned = {} as any;
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        cloned[key] = deepClone(obj[key]);
      }
    }
    return cloned;
  }
  
  return obj;
}

// 节流函数
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeoutId: NodeJS.Timeout | null = null;
  let lastExecTime = 0;
  
  return (...args: Parameters<T>) => {
    const currentTime = Date.now();
    
    if (currentTime - lastExecTime > delay) {
      func(...args);
      lastExecTime = currentTime;
    } else {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      timeoutId = setTimeout(() => {
        func(...args);
        lastExecTime = Date.now();
      }, delay - (currentTime - lastExecTime));
    }
  };
}

// 防抖函数
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeoutId: NodeJS.Timeout | null = null;
  
  return (...args: Parameters<T>) => {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      func(...args);
    }, delay);
  };
}

// 格式化错误堆栈
export function formatErrorStack(error: Error): string {
  if (!error.stack) {
    return '';
  }
  
  return error.stack
    .split('\n')
    .slice(0, 10) // 只取前10行
    .join('\n');
}

// 检查是否为采样数据
export function shouldSample(sampleRate: number = 1): boolean {
  return Math.random() < sampleRate;
}

// 获取性能指标
export function getPerformanceMetrics(): Partial<PerformanceInfo> {
  const metrics: Partial<PerformanceInfo> = {};
  
  if (window.performance && window.performance.timing) {
    const timing = window.performance.timing;
    metrics.loadTime = timing.loadEventEnd - timing.navigationStart;
    metrics.domContentLoadedTime = timing.domContentLoadedEventEnd - timing.navigationStart;
  }
  
  // 获取Web Vitals指标
  if ('PerformanceObserver' in window) {
    // FCP (First Contentful Paint)
    try {
      const fcpObserver = new PerformanceObserver((list) => {
        const entries = list.getEntries();
        if (entries.length > 0) {
          metrics.fcp = entries[0].startTime;
        }
      });
      fcpObserver.observe({ entryTypes: ['paint'] });
    } catch (e) {
      // 忽略错误
    }
    
    // LCP (Largest Contentful Paint)
    try {
      const lcpObserver = new PerformanceObserver((list) => {
        const entries = list.getEntries();
        if (entries.length > 0) {
          const lastEntry = entries[entries.length - 1];
          metrics.lcp = lastEntry.startTime;
        }
      });
      lcpObserver.observe({ entryTypes: ['largest-contentful-paint'] });
    } catch (e) {
      // 忽略错误
    }
    
    // FID (First Input Delay)
    try {
      const fidObserver = new PerformanceObserver((list) => {
        const entries = list.getEntries();
        if (entries.length > 0) {
          metrics.fid = entries[0].processingStart - entries[0].startTime;
        }
      });
      fidObserver.observe({ entryTypes: ['first-input'] });
    } catch (e) {
      // 忽略错误
    }
    
    // CLS (Cumulative Layout Shift)
    try {
      const clsObserver = new PerformanceObserver((list) => {
        let clsValue = 0;
        for (const entry of list.getEntries()) {
          if (!(entry as any).hadRecentInput) {
            clsValue += (entry as any).value;
          }
        }
        metrics.cls = clsValue;
      });
      clsObserver.observe({ entryTypes: ['layout-shift'] });
    } catch (e) {
      // 忽略错误
    }
  }
  
  return metrics;
} 